package com.timmy.bluetooth.connect;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.util.Log;

import com.timmy.bluetooth.utils.DebugLog;
import com.timmy.bluetooth.utils.Hex;

import java.util.UUID;

/**
 * Service for managing connection and data communication with a GATT server
 * hosted on a given Bluetooth LE device.
 */
public class BluetoothServer implements IBluetoothManager {
    private final static String TAG = BluetoothServer.class.getSimpleName();

    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private String mBluetoothDeviceAddress;
    private BluetoothGatt mBluetoothGatt;
    public int mConnectionState = STATE_DISCONNECTED;

    private BluetoothServiceCallback mCallback;

    private static final int STATE_DISCONNECTED = 0;
    private static final int STATE_CONNECTING = 1;
    private static final int STATE_CONNECTED = 2;

    public final static UUID UUID_CONTROL_ORDER_NOTIFY = UUID
            .fromString(GattAttributes.BRA_CHARACTERISTIC_NOTIFY);
    public final static UUID UUID_CONTROL_ORDER_WRITE = UUID
            .fromString(GattAttributes.BRA_CHARACTERISTIC_WRITE);

    private BluetoothGattCharacteristic mGattCharacteristicRead;


    public final static UUID UUID_CONTROL_ORDER_READ = UUID.
            fromString(GattAttributes.CHARACTERISTIC_READ_VERSION);

    private BluetoothGattCharacteristic mGattCharacteristicWrite;
    private BluetoothGattCharacteristic mGattCharacteristicNotify;

    Context context;

    public void addClientCallback(BluetoothServiceCallback mCallback) {
        this.mCallback = mCallback;
    }

    // Implements callback methods for GATT events that the app cares about. For
    // example,
    // connection change and services discovered.
    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                            int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                mConnectionState = STATE_CONNECTED;
                // Attempts to discover services after successful connection.
                DebugLog.e("Attempting to start service discovery:"
                        + mBluetoothGatt.discoverServices());

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                mConnectionState = STATE_DISCONNECTED;
                Log.i(TAG, "Disconnected from GATT server.");
                //mCallback.onConnectStatus(BluetoothConnectClientManager.ConnectStatus.STATUS_FAIL);
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            Log.w(TAG, "onServicesDiscovered received: " + status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                boolean result = getSupportedGattCharacteristic();

                if (result)
                    mCallback.onConnectStatus(BluetoothConnectClientManager.ConnectStatus.STATUS_OK);
                else
                    mCallback.onConnectStatus(BluetoothConnectClientManager.ConnectStatus.STATUS_FAIL);
            } else {
                mCallback.onConnectStatus(BluetoothConnectClientManager.ConnectStatus.STATUS_FAIL);
            }
        }


        @Override
        public void onCharacteristicRead(BluetoothGatt gatt,
                                         BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                if (mGattCharacteristicRead == characteristic) {
                    mCallback.onVersion(characteristic.getValue());
                }
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic) {
            if (mGattCharacteristicNotify == characteristic) {
                mCallback.onReceive(characteristic.getValue());
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt,
                                          BluetoothGattCharacteristic characteristic, int status) {
            //Log.d("Le", "发送成功");
            super.onCharacteristicWrite(gatt, characteristic, status);
        }

        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
        }
    };


    /**
     * Initializes a reference to the local Bluetooth adapter.
     *
     * @return Return true if the initialization is successful.
     */
    public boolean initialize(Context context) {
        // For API level 18 and above, get a reference to BluetoothAdapter
        // through
        // BluetoothManager.
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
            if (mBluetoothManager == null) {
                Log.e(TAG, "Unable to initialize BluetoothManager.");
                return false;
            }
        }

        this.context = context;

        mBluetoothAdapter = mBluetoothManager.getAdapter();
        //蓝牙是否能开启
        if (mBluetoothAdapter == null) {
            Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
            return false;
        }

        return true;
    }

    /**
     * Connects to the GATT server hosted on the Bluetooth LE device.
     *
     * @param address The device address of the destination device.
     * @return Return true if the connection is initiated successfully. The
     * connection result is reported asynchronously through the
     * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
     * callback.
     */
    public boolean connect(Context context, final String address) {
        if (mBluetoothAdapter == null || address == null) {
            Log.w(TAG,
                    "BluetoothAdapter not initialized or unspecified address.");
            return false;
        }

        // Previously connected device. Try to reconnect.
        if (mBluetoothDeviceAddress != null
                && address.equals(mBluetoothDeviceAddress)
                && mBluetoothGatt != null) {
            Log.d(TAG,
                    "Trying to use an existing mBluetoothGatt for connection.");
            if (mBluetoothGatt.connect()) {
                mConnectionState = STATE_CONNECTING;
                return true;
            } else {
                return false;
            }
        }

        final BluetoothDevice device = mBluetoothAdapter
                .getRemoteDevice(address);
        if (device == null) {
            Log.w(TAG, "Device not found.  Unable to connect.");
            return false;
        }
        // We want to directly connect to the device, so we are setting the
        // autoConnect
        // parameter to false.
        mBluetoothGatt = device.connectGatt(context, false, mGattCallback);
        Log.d(TAG, "Trying to create a new connection.");
        mBluetoothDeviceAddress = address;
        mConnectionState = STATE_CONNECTING;
        return true;
    }

    public boolean getConnectStatus() {
        if (mConnectionState == STATE_CONNECTED) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Disconnects an existing connection or cancel a pending connection. The
     * disconnection result is reported asynchronously through the
     * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
     * callback.
     */
    public void disconnect() {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.disconnect();

        mConnectionState = STATE_DISCONNECTED;
    }

    /**
     * After using a given BLE device, the app must call this method to ensure
     * resources are released properly.
     */
    public void close() {
        if (mBluetoothGatt == null) {
            return;
        }
        mBluetoothGatt.close();
        mBluetoothGatt = null;
    }

    /**
     * Request a read on a given {@code BluetoothGattCharacteristic}. The read
     * result is reported asynchronously through the
     * {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
     * callback.
     *
     * @param characteristic The characteristic to read from.
     */
    public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.readCharacteristic(characteristic);
    }

    /**
     * Enables or disables notification on a give characteristic.
     *
     * @param
     * @param enabled If true, enable notification. False otherwise.
     */
    public void setCharacteristicNotification(boolean enabled) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }

        if (mGattCharacteristicNotify != null) {
            if (mBluetoothGatt.setCharacteristicNotification(
                    mGattCharacteristicNotify, enabled))
                Log.w(TAG, "set notify succ");
            BluetoothGattDescriptor descriptor = mGattCharacteristicNotify
                    .getDescriptor(UUID
                            .fromString(GattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            mBluetoothGatt.writeDescriptor(descriptor);
        } else {
            DebugLog.d("mGattCharacteristicNotify is null");
        }
    }


    public void WriteData(byte[] data) {
        Log.i("WriteData", Hex.bytesToHexString(data));

        if (mBluetoothGatt != null && mGattCharacteristicWrite != null) {
            //DebugLog.e("data" + Hex.bytesToHexString(data));
            mGattCharacteristicWrite.setValue(data);

            try {
                mBluetoothGatt.writeCharacteristic(mGattCharacteristicWrite);
            } catch (RuntimeException e) {
                DebugLog.e("RuntimeException :" + e.getMessage());
            }
        }
    }

    /**
     * @return true
     */
    public boolean readRssi() {
        if (mBluetoothGatt != null)
            return mBluetoothGatt.readRemoteRssi();
        else
            return false;
    }


    public boolean getVersion() {

        if (mBluetoothAdapter == null || mBluetoothGatt == null || mGattCharacteristicRead == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return false;
        }


        return mBluetoothGatt.readCharacteristic(mGattCharacteristicRead);

    }


    /**
     * Retrieves a list of supported GATT services on the connected device. This
     * should be invoked only after {@code BluetoothGatt#discoverServices()}
     * completes successfully.
     *
     * @return A {@code List} of supported services.
     */
    public boolean getSupportedGattCharacteristic() {
        if (mBluetoothGatt == null)
            return false;

        BluetoothGattService server = mBluetoothGatt.getService(UUID
                .fromString(GattAttributes.BRA_CONTROL_MOVEMENT_SERVER));
        BluetoothGattService devicesServer = mBluetoothGatt.
                getService(UUID.fromString(GattAttributes.DEVICES_SERVER));

        if (devicesServer != null) {

            mGattCharacteristicRead = devicesServer.getCharacteristic(UUID_CONTROL_ORDER_READ);
        }

        if (server != null) {
            mGattCharacteristicWrite = server
                    .getCharacteristic(UUID_CONTROL_ORDER_WRITE);
            mGattCharacteristicNotify = server
                    .getCharacteristic(UUID_CONTROL_ORDER_NOTIFY);

            return true;
        } else {
            return false;
        }
    }


}
